<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/26
 * Time: 16:56
 */

namespace app\admin\controller;

use app\model\AdminInfo as ModelAdminInfo;
use app\model\AdminPassport as ModelAdminPassport;
use app\model\UserPassport as ModelUserPassport;
use app\model\CourierPassport as ModelCourierPassport;
use app\model\UserOrder as ModelUserOrder;
use app\model\WithdrawLog as ModelWithdrawLog;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\DriverOrder as ModelDriverOrder;
use app\model\StationOrder as ModelStationOrder;
use app\model\UserInfo as ModelUserInfo;
use app\model\CourierInfo as ModelCourierInfo;
use app\model\DriverInfo as ModelDriverInfo;
use app\model\StationPassport as ModelStationPassport;
use app\model\SysSetting as ModelSysSetting;

use think\Db;


class Home extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页->账户设置->修改密码 \n
     * URI : /admin/admin.modify.pwd
     * @param :
     *  name          |  type  | null | description
     * ---------------|--------|------|-------------
     *  passport      | string | 必填  | 凭证
     *  headPortrait  | string | 选填  | 头像
     *  password      | string | 必填  | 旧密码
     *  newPassword   | string | 必填  | 新密码
     *  newPasswordTo | string | 必填  | 再次新密码
     *
     * @return :
     *  name        |  type  | description
     * -------------|--------|-------------
     *  ----------- | ------ | 无
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function adminModifyPassword(){

        $str_head_portrait = $this->_getContentParams('headPortrait'); // 头像
        $str_password = $this->_getContentParams('password'); // 旧密码
        _toValidate('login_pwd', $str_password, 21004);
        $arr_pwd_info = ModelAdminInfo::getInstance()->toFind(['id' => $this->admin_id], 'password,pwd_key');
        _toCompare(passwordEncryption($str_password,$arr_pwd_info['pwd_key']), '!=', $arr_pwd_info['password'], 21006);
        $str_new_password = $this->_getContentParams('newPassword'); //新密码
        _toValidate('login_pwd', $str_new_password, 21004);
        $str_new_password_to = $this->_getContentParams('newPasswordTo'); //再次密码
        _toCompare($str_new_password_to, '!=', $str_new_password, 21005);
        ModelAdminInfo::getInstance()->toUpdate(['id' => $this->admin_id], ['password' => passwordEncryption($str_new_password,$arr_pwd_info['pwd_key']), 'head_portrait' => $str_head_portrait]);
        _returnData();
    }

    /**
     * 首页->系统信息 \n
     * URI : /admin/stem.information
     * @param :
     *  name       | type   | null | description
     * ------------|--------|------|-------------
     *  ---------- | ------ | 无
     *
     * @return :
     *  name       | type   | description
     * ------------|--------|-------------
     *  list       | array  | 列表
     *
     * list:
     *  name                | type   | description
     * ---------------------|--------|-------------
     *  systemServer        | string | 服务器操作系统
     *  webServer           | string | Web 服务器
     *  phpVersion          | string | PHP 版本
     *  sqlVersion          | string | MySQL 版本
     *  safeMode            | string | 安全模式
     *  safeGid             | string | 安全模式GID
     *  socketSupport       | string | socket支持
     *  timeZone            | string | 时区设置
     *  gdVersion           | string | GD 版本
     *  zlibSupport         | string | Zlib 支持
     *  ipLibraryVersion    | string | IP 库版本
     *  fileUpload          | string | 文件上传的最大大小:
     *  programVersion      | string | v2.2.2 RELEASE 20170629
     *  installationDate    | string | 安装日期
     *  codeUtf             | string | 编码
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stemInformation(){
        $arr_data = [];
        $arr_data['systemServer']      = 'Linux (114.55.34.251)';  //服务器操作系统
        $arr_data['webServer']         = 'nginx/1.10.2';           //Web 服务器
        $arr_data['phpVersion']        = '5.6.30';                 //PHP 版本
        $arr_data['sqlVersion']        = '5.6.17';                 //MySQL 版本
        $arr_data['safeMode']          = '否';                     //安全模式
        $arr_data['safeGid']           = '否';                     //安全模式GID
        $arr_data['socketSupport']     = '是';                     //socket支持
        $arr_data['timeZone']          = 'Asia/Shanghai';          //时区设置
        $arr_data['gdVersion']         = 'GD2 ( JPEG GIF PNG)';    //GD 版本
        $arr_data['zlibSupport']       = '是';                     //Zlib 支持
        $arr_data['ipLibraryVersion']  = '20080405';               //IP 库版本
        $arr_data['fileUpload']        = '40M';                    //文件上传的最大大小:
        $arr_data['programVersion']    = 'v2.2.2 RELEASE 20080405';//v2.2.2 RELEASE 20080405
        $arr_data['installationDate']  = '2018-04-05';             //安装日期
        $arr_data['codeUtf']           = 'UTF-8';                  //编码
        _returnData(['list' => $arr_data]);
    }

    /**
     * 首页->登录日志 \n
     * URI : /admin/login.log.list
     * @param :
     *  name     | type   | null | description
     * ----------|--------|------|-------------
     *  page     | int    | 必填  | 页码
     *  listRows | int    | 必填  | 一页的条数
     *
     * @return
     *  name       | type   | description
     * ------------|--------|-------------
     *  totalPages | string | 总页数
     *  list       | array  | 列表
     *
     * list:
     *  name        | type   | description
     * -------------|--------|-------------
     *  platform    | string | 登录工具
     *  ip          | string | ip
     *  gmt_create  | string | 登录时间
     *  province    | string | 省
     *  city        | string | 市
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginLogList(){

        $int_now_page = $this->_getContentParams('page'); // 当前页码
        if (empty($int_now_page)){
            $int_now_page = 1;
        }
        _toValidate('id', $int_now_page, 10005);


        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        if (empty($int_list_rows)){
            $int_list_rows = 10;
        }
        _toValidate('id', $int_list_rows, 10006);
        $block = $this->_getContentParams('block');
        //$block =4;
        switch ($block){
            case 1://系统登录日志
                $adminId = $this->_getContentParams('adminId');
                //$adminId =1;
                $arr_where = [
                    'admin_id' => $adminId
                ];
                $int_total_rows = ModelAdminPassport::getInstance()->toCount($arr_where);
                $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
                _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
                $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
                $str_field = 'platform,ip,gmt_create as gmtCreate';
                $arr_list = ModelAdminPassport::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
                break;
            case 2://用户登录日志
                $userId = $this->_getContentParams('userId');
                //$userId =1;
                $arr_where = [
                    'user_id' => $userId
                ];
                $int_total_rows = ModelUserPassport::getInstance()->toCount($arr_where);
                $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
                _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
                $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
                $str_field = 'platform,ip,gmt_create as gmtCreate';
                $arr_list = ModelUserPassport::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
                break;
            case 3://快递员登陆日志
                $courierId = $this->_getContentParams('courierId');
                //$courierId =2;
                $arr_where = [
                    'courier_id' => $courierId
                ];
                $int_total_rows = ModelCourierPassport::getInstance()->toCount($arr_where);
                $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
                _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
                $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
                $str_field = 'platform,ip,gmt_create as gmtCreate';
                $arr_list = ModelCourierPassport::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
                break;
            case 4://站点登录日志
                $stationId = $this->_getContentParams('stationId');
                //$stationId = 1;
                $arr_where = [
                    'station_id' => $stationId
                ];
                $int_total_rows = ModelStationPassport::getInstance()->toCount($arr_where);
                $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
                _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
                $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
                $str_field = 'platform,ip,gmt_create as gmtCreate';
                $arr_list = ModelStationPassport::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, 'gmt_create desc');
                break;
            default:
                break;
        }

        foreach($arr_list as &$value){
            $arr_address = $this->GetIpLookup($value['ip']);
            $value['province'] = $arr_address['province'];
            $value['city'] = $arr_address['city'];
        }
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * IP查找地址
     * @param string $ip
     * @return bool|mixed|string
     */
    public function GetIpLookup($ip = ''){
        if(empty($ip)){
            return '请输入IP地址';
        }
        $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
        if(empty($res)){ return false; }
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if(!isset($jsonMatches[0])){ return false; }
        $json = json_decode($jsonMatches[0], true);
        if(isset($json['ret']) && $json['ret'] == 1){
            $json['ip'] = $ip;
            unset($json['ret']);
        }else{
            return false;
        }
        return $json;
    }

    /**
     * 系统首页数据
     * uri:/admin/system.homePage
     */
    public function systemHomePage(){
        $currentTime=date('Ymd',time());//今日时间
        $yesterdayTime=date('Ymd',strtotime('-1 day',time()));//昨日时间
        $nearlySevenDaysTime=date('Ymd',strtotime('-7 day',time()));//近七天时间
        $thisMonth=date('Ym',time());//本月时间
        //今日订单
        $todayOrder = ModelUserOrder::getInstance()->toFind("DATE_FORMAT(gmt_create,'%Y%m%d')=$currentTime",'count(*) AS todayOrder');
        //今日订单总额
        $todayOrderAmount = ModelUserOrder::getInstance()->toFind("DATE_FORMAT(gmt_create,'%Y%m%d')=$currentTime",'ifnull(sum(order_amount),0) AS todayOrderAmount');
        //昨日订单总额
        $yesterdayOrderAmount = ModelUserOrder::getInstance()->toFind("DATE_FORMAT(gmt_create,'%Y%m%d')=$yesterdayTime",'ifnull(sum(order_amount),0) as yesterdayOrderAmount');
        //近7天销售总额
        $nearlySevenDaysAmount = ModelUserOrder::getInstance()->toFind("DATE_FORMAT(gmt_create,'%Y%m%d')>=$nearlySevenDaysTime",'ifnull(sum(order_amount),0) AS nearlySevenDaysAmount');
        //预提现总额
        $withholding = ModelWithdrawLog::getInstance()->toFind("state=0",'ifnull(sum(money),0) AS withholding');
        //快递员订单
        $courierOrder = ModelCourierOrder::getInstance()->toCount('');
        //站点订单
        $stationOrder = ModelStationOrder::getInstance()->toCount('');
        //司机订单
        $driverOrder = ModelDriverOrder::getInstance()->toCount('');
        //未接订单
        $notPickUpOrder = ModelUserOrder::getInstance()->toCount('order_state=10 or order_state=60');
        //今日新增用户
        $todayUser = ModelUserInfo::getInstance()->toCount("DATE_FORMAT(gmt_create,'%Y%m%d')=$currentTime");
        //昨日新增用户
        $yesterdayUser = ModelUserInfo::getInstance()->toCount("DATE_FORMAT(gmt_create,'%Y%m%d')=$yesterdayTime");
        //本月新增用户
        $thisMonthUser = ModelUserInfo::getInstance()->toCount("DATE_FORMAT(gmt_create,'%Y%m')=$thisMonth");
        //会员总数
        $userCount = ModelUserInfo::getInstance()->toCount('');
        //待审核快递员
        $toAuditCourier = ModelCourierInfo::getInstance()->toCount('auth_state=2');
        //待审核司机
        $toAuditDriver = ModelDriverInfo::getInstance()->toCount('auth_state=2');
        //待审核官服快递
        $toAuditOfficialCourier = ModelCourierInfo::getInstance()->toCount('is_official=2');
        $data=[
            'todayOrder'=>$todayOrder['todayOrder'],
            'todayOrderAmount'=>$todayOrderAmount['todayOrderAmount'],
            'yesterdayOrderAmount'=>$yesterdayOrderAmount['yesterdayOrderAmount'],
            'nearlySevenDaysAmount'=>$nearlySevenDaysAmount['nearlySevenDaysAmount'],
            'withholding'=>$withholding['withholding'],
            'courierOrder'=>$courierOrder,
            'driverOrder'=>$driverOrder,
            'stationOrder'=>$stationOrder,
            'notPickUpOrder'=>$notPickUpOrder,
            'todayUser'=>$todayUser,
            'yesterdayUser'=>$yesterdayUser,
            'thisMonthUser'=>$thisMonthUser,
            'userCount'=>$userCount,
            'toAuditCourier'=>$toAuditCourier,
            'toAuditDriver'=>$toAuditDriver,
            'toAuditOfficialCourier'=>$toAuditOfficialCourier
        ];
        _returnData(['homePageData'=>$data]);
    }

    /**
     * 结算设置
     * uri:/admin/settlement.setUpThe
     */
    public function settlementSetUpThe(){
        $courier_settlement = ModelSysSetting::getInstance()->getValue('courier_settlement');
        $station_settlement = ModelSysSetting::getInstance()->getValue('station_settlement');
        $driver_settlement = ModelSysSetting::getInstance()->getValue('driver_settlement');
        $data = [
            'courierSettlement'=>$courier_settlement,
            'stationSettlement'=>$station_settlement,
            'driverSettlement'=>$driver_settlement
        ];
        _returnData($data);
    }

    /**
     * 结算设置修改
     * uri:/admin/settlement.setUpTheModify
     */
    public function settlementSetUpTheModify(){
        $courier_settlement = $this->_getContentParams('courierSettlement');
        _toCompare(empty($courier_settlement),'==',true,20004);
        $station_settlement = $this->_getContentParams('stationSettlement');
        _toCompare(empty($station_settlement),'==',true,20005);
        $driver_settlement = $this->_getContentParams('driverSettlement');
        _toCompare(empty($driver_settlement),'==',true,20006);
        $arr_where = [
            'courier_settlement'=>$courier_settlement,
            'station_settlement'=>$station_settlement,
            'driver_settlement'=>$driver_settlement
        ];
        foreach ($arr_where as $key=>$value){
            $arr=['value'=>$value];
            ModelSysSetting::getInstance()->toUpdate("`key`='$key'",$arr);
        }
        _returnData();
    }

    /**
     * 押金设置
     * uri:/admin/deposit.setUpThe
     */
    public function depositSetUpThe(){
        $courier_deposit = ModelSysSetting::getInstance()->getValue('courier_deposit');
        $station_deposit = ModelSysSetting::getInstance()->getValue('station_deposit');
        $driver_deposit = ModelSysSetting::getInstance()->getValue('driver_deposit');
        $data = [
            'courierDeposit'=>$courier_deposit,
            'stationDeposit'=>$station_deposit,
            'driverDeposit'=>$driver_deposit
        ];
        _returnData($data);
    }

    /**
     * 押金设置修改
     * uri:/admin/deposit.setUpTheModify
     */
    public function depositSetUpTheModify(){
        $courier_deposit = $this->_getContentParams('courierDeposit');
        _toCompare(empty($courier_deposit),'==',true,20001);
        $station_deposit = $this->_getContentParams('stationDeposit');
        _toCompare(empty($station_deposit),'==',true,20002);
        $driver_deposit = $this->_getContentParams('driverDeposit');
        _toCompare(empty($driver_deposit),'==',true,20003);
        $arr_where = [
            'courier_deposit'=>$courier_deposit,
            'station_deposit'=>$station_deposit,
            'driver_deposit'=>$driver_deposit
        ];
        foreach ($arr_where as $key=>$value){
            $arr=['value'=>$value];
            ModelSysSetting::getInstance()->toUpdate("`key`='$key'",$arr);
        }
        _returnData();
    }
}